// JWT认证检查
const checkAuth = () => {
    console.log('dispatch-events.html: 开始认证检查');
    
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        console.log('用户未认证，重定向到登录页');
        AuthManager.redirectToLogin();
        return;
    }
    
    // 检查token有效性
    AuthManager.verifyToken()
        .then(() => {
            console.log('Token验证成功，加载事件');
            loadEvents();
        })
        .catch(error => {
            console.error('Token验证失败:', error);
            AuthManager.redirectToLogin();
        });
};
document.addEventListener('DOMContentLoaded', checkAuth);

function loadEvents() {
    const headers = {};
    if (window.AuthManager && window.AuthManager.getAuthHeaders) {
        Object.assign(headers, window.AuthManager.getAuthHeaders());
    }
    
    fetch('/ercms/dispatch/api/events', {
        headers: headers
    })
        .then(r=>r.json())
        .then(res=>{
            if(res.success && res.data) {
                const list = res.data.content || res.data;
                document.getElementById('eventListBody').innerHTML = list.map(e=>`<tr>
                    <td>${e.id}</td>
                    <td>${e.title}</td>
                    <td>${e.eventType ? e.eventType.name : ''}</td>
                    <td>${getPriorityText(e.priority)}</td>
                    <td>${getSeverityText(e.severity)}</td>
                    <td>${getStatusText(e.status)}</td>
                    <td>${e.reporter ? e.reporter.realName : ''}</td>
                    <td><a class='btn btn-sm btn-info' href='/ercms/dispatch/event/${e.id}'>详情</a></td>
                `).join('');
            } else {
                document.getElementById('eventListBody').innerHTML = '<tr><td colspan="8">暂无数据</td></tr>';
            }
        });
}

function getPriorityText(priority) {
    return { 'HIGH': '高', 'MEDIUM': '中', 'LOW': '低' }[priority] || priority;
}

function getSeverityText(severity) {
    return { 'CRITICAL': '严重', 'SEVERE': '严重', 'HIGH': '高', 'MODERATE': '中等', 'MEDIUM': '中等', 'MINOR': '轻微', 'LOW': '低' }[severity] || severity;
}

function getStatusText(status) {
    const texts = {
        'PENDING': '待处理',
        'ASSIGNED': '已指派',
        'ACCEPTED': '已接收',
        'EN_ROUTE': '正在前往',
        'ARRIVED': '到达现场',
        'IN_PROGRESS': '开始处理',
        'COMPLETED': '完成任务',
        'RETURNING': '正在返程',
        'RESOLVED': '已解决',
        'CLOSED': '已关闭'
    };
    return texts[status] || status;
} 